package com.ssm.zy.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 郑智辰~
 * @version 1.0
 *
 * WebSocket “双人聊天” 处理程序
 */
@Slf4j
@Component
public class WebSocketDoubleChatHandler extends AbstractWebSocketHandler {
    private static Map<String,WebSocketSession> connectionPool;

    static {
        connectionPool = new ConcurrentHashMap<String,WebSocketSession>();
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        //获取登录用户名
        String userName = this.getUserName(session);
        if (userName != null) {
            connectionPool.put(userName, session);
            log.info("有新用户加入，username={}, 当前在线人数为：{}", userName,connectionPool.size());
            // 后台发送消息给所有的客户端

        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
    }

    //获取登录用户名信息
    public String getUserName(WebSocketSession session) {
        //获取对应的请求路径对象URI
        URI uri = session.getUri();
        if (uri != null){
            //获取路径字符串
            String path = uri.getPath();
            //截取路径中username [/xhs-double/{username}]
            String username = path.substring(path.lastIndexOf("/") + 1);
            //添加到session域中
            session.getAttributes().put("username", username);
            //返回
            return username;
        }
        return null;
    }

    //通知在线的好友,好友登录信息
    public void sendMessage(WebSocketSession session){

    }
}
